//
//  AppGlobalClass.m
//  鱼鱼APP
//
//  Created by User on 15/1/13.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "AppGlobalClass.h"

#import <CommonCrypto/CommonDigest.h>

static AFHTTPRequestOperationManager *__manager;

@implementation AppGlobalClass

/*!
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (void)exitLogin
{
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userCd"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"password"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"token"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"idCardVStatus"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"mobileVStatus"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"payPasswordVStatus"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"GesturePsd"];//删除手势密码
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"mobile"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"cardVStatus"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"memberNo"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"memberType"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSString *)SharedURL:(NSString *)url
{
 
    if([url isEqualToString:BANNER_URL])
        return Index_Url_Test_Http;
    else
        return Index_Url_Test;
}

+ (NSString *) SharedNullToNSString : (id) object
{
    if ([object isKindOfClass:[NSString class]])
    {
        return object;
    }
    
    else return @"";
}


/**
 *  获取数据的方法（POST方法）
 *
 *  @param actionUrlStr   每个接口的地址
 *  @param dic            储存键值对的字典
 *  @param viewController 加载在哪个view上
 *  @param success        成功返回的数据
 *  @param failure        失败的参数
 *  @param networkerror   网络错误
 *
 *  @return 返回键值对
 */

+(NSDictionary *)PostDataWithNSstring : (NSString *)actionUrlStr
                       withDictionary : (NSMutableDictionary *) dic
                 withUIViewController : (UIViewController *)viewController
                              success : (void (^)(NSDictionary* dictionary))success
                              failure : (void (^)(NSError *error))failure
                         networkerror : (void (^)(NSString *networkerror))networkerror
{
    NSString *URL = [NSString stringWithFormat:@"%@%@",[self SharedURL:actionUrlStr],actionUrlStr];
    
    if ( [CheckNetWork isExistenceNetwork] )
    {
        // AFNetworking 2.3.3
        AFHTTPRequestOperationManager *httpClient = [AFHTTPRequestOperationManager manager];
        __manager = httpClient;
        [httpClient POST:URL
              parameters:dic
                 success:^(AFHTTPRequestOperation *operation, id responseObject) {
                     NSDictionary *dictionary = responseObject;
                     if(dictionary)
                     {
                         success(dictionary);
                     }
                 }
                 failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                 }];
    }
    return nil;
}

+(NSDictionary *)GetDataWithNSstring : (NSString *)actionUrlStr
                       withDictionary : (NSDictionary *) dic
                              success : (void (^)(NSDictionary* dictionary))success
                              failure : (void (^)(NSError *error))failure
                         networkerror : (void (^)(NSString *networkerror))networkerror
{
    NSString *URL = actionUrlStr;
    URL = [URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if ( [CheckNetWork isExistenceNetwork] )
    {
        // AFNetworking 2.3.3
        
//        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy]; // 支持https协议
//        securityPolicy.allowInvalidCertificates = TRUE;
        
        AFHTTPRequestOperationManager *httpClient = [AFHTTPRequestOperationManager manager];
     //   httpClient.securityPolicy = securityPolicy;
        __manager = httpClient;
        [__manager.requestSerializer setValue:@"f4b1dbb4929247dc8bd01f88533259b8" forHTTPHeaderField:@"apikey"];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
            [httpClient GET:URL
                  parameters:dic
                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                         NSDictionary *dictionary = responseObject;
                         if(dictionary)
                         {
                             success(dictionary);
                         }
                         else
                         {
                             ALERT_VIEW(@"服务器错误");
                         }
                     }
                     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         failure(error);
                         UIWindow *window = [[UIApplication sharedApplication]keyWindow];
                         
                         MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:TRUE];
                         hud.mode = MBProgressHUDModeText;
                         hud.labelText = @"网络错误";
                         hud.labelFont = [UIFont systemFontOfSize:13.0f];
                         [hud hide:TRUE afterDelay:2.0f];
                     }];
        });
    }
    else
    {
        networkerror(@"网络错误");
        
        UIWindow *window = [[UIApplication sharedApplication]keyWindow];
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:TRUE];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"网络错误";
        hud.labelFont = [UIFont systemFontOfSize:13.0f];
        [hud hide:TRUE afterDelay:2.0f];
    }
    return nil;
}

+(NSDictionary *)PostDataWithNSstring : (NSString *)actionUrlStr
                       withDictionary : (NSDictionary *) dic
                              success : (void (^)(NSDictionary* dictionary))success
                              failure : (void (^)(NSError *error))failure
                         networkerror : (void (^)(NSString *networkerror))networkerror
{
    NSString *URL = [NSString stringWithFormat:@"%@%@",[self SharedURL:actionUrlStr],actionUrlStr];
    URL = [URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if ( [CheckNetWork isExistenceNetwork] )
    {
        
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy]; // 支持https协议
        securityPolicy.allowInvalidCertificates = TRUE;
        
        // AFNetworking 2.3.3
        AFHTTPRequestOperationManager *httpClient = [AFHTTPRequestOperationManager manager];
        httpClient.securityPolicy = securityPolicy;
        __manager = httpClient;

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
            [httpClient POST:URL
                  parameters:dic
                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                         NSDictionary *dictionary = responseObject;
                         if(dictionary)
                         {
                             success(dictionary);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
                         }
                         else
                         {
                             ALERT_VIEW(@"服务器异常");
                         }
                     }
                     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         failure(error);
                         NSDictionary *dic = [AppGlobalClass dictionaryWithJsonString:operation.responseString];
                         if (dic) {
                             NSString *message = [dic objectForKey:@"message"];
                             if (message) {
                                 if ([message isEqualToString:@"登录失败，请重新登录"]) {
                                     [[NSNotificationCenter  defaultCenter] postNotificationName:@"reLogin" object:nil];                         }
                                 else{
                                     UIWindow *window = [[UIApplication sharedApplication]keyWindow];
                                     
                                     MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:TRUE];
                                     hud.mode = MBProgressHUDModeText;
                                     hud.labelText = message;
                                     hud.labelFont = [UIFont systemFontOfSize:13.0f];
                                     [hud hide:TRUE afterDelay:2.0f];

                                 }
                             }

                         }
                         else
                         {
                             if(![actionUrlStr isEqualToString:LOGIN_URL])
                             {
                                 UIWindow *window = [[UIApplication sharedApplication]keyWindow];
                                 
                                 MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:TRUE];
                                 hud.mode = MBProgressHUDModeText;
                                 hud.labelText = @"连接服务器失败";
                                 hud.labelFont = [UIFont systemFontOfSize:13.0f];
                                 [hud hide:TRUE afterDelay:2.0f];
#warning 这边应该有撤销HUD
                                 [MBProgressHUD hideAllHUDsForView:window animated:TRUE];
                             }

                         }
                         
                     }];
        });
    }
    else
    {
        networkerror(@"网络异常");
        UIWindow *window = [[UIApplication sharedApplication]keyWindow];
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:TRUE];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"网络异常";
        hud.labelFont = [UIFont systemFontOfSize:13.0f];
        [hud hide:TRUE afterDelay:2.0f];
    }
    return nil;
}

+ (BOOL)isPureNumandCharacters:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return TRUE;
}

+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);// This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+ (void)deleteCookie
{
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
}

+ (BOOL) validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+ (BOOL)validateTel:(NSString *)tel
{
    NSString *telStr = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    NSPredicate *telTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", telStr];
    return [telTest evaluateWithObject:tel];
}

+ (CGFloat)getLabelHeight:(NSString *)string font:(UIFont *)font width:(CGFloat)width
{
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
    CGSize textSize = CGSizeMake(width, 0.0f);
    textSize = [string boundingRectWithSize:textSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading  attributes:dict context:nil].size;
    return textSize.height;
}


+(void)cancleRequest
{
    if (__manager.operationQueue!=nil) {
        [__manager.operationQueue cancelAllOperations];
        __manager = nil;
    }
}
@end
